package com.example.mahao

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.selects.select
import java.io.BufferedWriter
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStreamWriter


class MainActivity : AppCompatActivity() {

    private var isCalculating = false
    private var currentIndex = 0
    private lateinit var resultTextView: TextView
    private lateinit var startButton: Button
    private lateinit var pauseButton: Button
    private lateinit var resumeButton: Button
    private lateinit var stopButton: Button
    private lateinit var minInput: EditText
    private lateinit var maxInput: EditText
    private var job: Job? = null
    private val pauseChannel = Channel<Unit>(Channel.CONFLATED) // 用于控制暂停和恢复

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        resultTextView = findViewById(R.id.resultTextView)
        startButton = findViewById(R.id.startButton)
        pauseButton = findViewById(R.id.pauseButton)
        resumeButton = findViewById(R.id.resumeButton)
        stopButton = findViewById(R.id.stopButton)
        minInput = findViewById(R.id.minInput)
        maxInput = findViewById(R.id.maxInput)

        startButton.setOnClickListener {
            val min = minInput.text.toString().toIntOrNull()
            val max = maxInput.text.toString().toIntOrNull()

            if (min != null && max != null && min < max) {
                startPrimeCalculation(min, max)
            } else {
                Toast.makeText(this, "请输入有效的最小和最大数字", Toast.LENGTH_SHORT).show()
            }
        }

        pauseButton.setOnClickListener {
            pauseCalculation()
        }

        resumeButton.setOnClickListener {
            resumeCalculation()
        }

        stopButton.setOnClickListener {
            stopCalculation()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)  // 加载菜单
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_history -> {
                // 启动 SecondActivity
                val intent = Intent(this, SecondActivity::class.java)
                startActivity(intent)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun startPrimeCalculation(min: Int, max: Int) {
        if (isCalculating) return

        isCalculating = true
        currentIndex = min
        resultTextView.text = "计算中..."

        startButton.isEnabled = false
        pauseButton.isEnabled = true
        stopButton.isEnabled = true
        resumeButton.isEnabled = false

        // 使用 GlobalScope 启动协程
        job = CoroutineScope(Dispatchers.IO).launch {
            calculatePrimesInRange(min, max)
        }
    }

    private suspend fun calculatePrimesInRange(min: Int, max: Int) {
        val primeList = mutableListOf<String>() // 用来存储计算的素数

        for (i in currentIndex..max) {
            if (!isCalculating) break // 如果停止计算

            // 使用 select 处理暂停信号和延迟
            select<Unit> {
                pauseChannel.onReceive {
                    // 挂起，直到收到恢复信号
                    // 暂停时只需要挂起这里
                    pauseChannel.receive()
                }
                onTimeout(1000) {
                    // 模拟耗时操作
                    val resultText = if (isPrime(i)) {
                        "$i 是素数"
                    } else {
                        "$i 不是素数"
                    }

                    // 记录计算的素数
                    if (isPrime(i)) {
                        primeList.add(i.toString())  // 保存素数
                    }

                    withContext(Dispatchers.Main) {
                        resultTextView.text = resultText
                    }

                    currentIndex = i + 1
                }
            }
        }

        // 保存素数结果到文件
        savePrimesToFile(primeList)

        withContext(Dispatchers.Main) {
            // 完成计算后重置按钮状态
            startButton.isEnabled = true
            pauseButton.isEnabled = false
            stopButton.isEnabled = false
            resumeButton.isEnabled = false
        }
    }

    private fun savePrimesToFile(primeList: List<String>) {
        try {
            val fileOutputStream: FileOutputStream = openFileOutput("prime_results.txt", MODE_APPEND) // 修改为追加
            val writer = BufferedWriter(OutputStreamWriter(fileOutputStream))

            for (prime in primeList) {
                writer.write("$prime\n")  // 每个素数单独一行
            }

            writer.close()  // 关闭文件流
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun isPrime(number: Int): Boolean {
        if (number <= 1) return false
        for (i in 2..Math.sqrt(number.toDouble()).toInt()) {
            if (number % i == 0) return false
        }
        return true
    }

    private fun pauseCalculation() {
        if (isCalculating) {
            // 向暂停通道发送信号，挂起协程
            pauseChannel.trySend(Unit) // 发送信号，暂停计算
            resultTextView.append("\n计算已暂停")
            pauseButton.isEnabled = false
            resumeButton.isEnabled = true
        }
    }

    private fun resumeCalculation() {
        if (isCalculating) {
            // 向暂停通道发送信号，恢复计算
            pauseChannel.trySend(Unit) // 发送恢复信号
            resultTextView.append("\n计算继续")
            pauseButton.isEnabled = true
            resumeButton.isEnabled = false
        }
    }

    private fun stopCalculation() {
        if (isCalculating) {
            isCalculating = false
            job?.cancel() // 取消协程
            resultTextView.text = "计算已停止"

            startButton.isEnabled = true
            pauseButton.isEnabled = false
            stopButton.isEnabled = false
            resumeButton.isEnabled = false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        job?.cancel()
    }
}

